package com.itzhoujun.jtimer.controller;

import com.itzhoujun.jtimer.entity.Stock;
import com.itzhoujun.jtimer.mapper.StockMapper;
import com.itzhoujun.jtimer.utils.Response;
import com.itzhoujun.jtimer.utils.TableSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/Stock")
public class StockController {

    @Autowired
    private StockMapper stockMapper;


    @GetMapping("/index")
    public String index(){
        return "stock/index";
    }
   
    @PostMapping("/doUpdate")
    @ResponseBody
    public Object doUpdate(@Valid Stock stock, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return Response.error(bindingResult.getFieldError().getDefaultMessage());
        }
        Integer id = stock.getId();
        int num;
        if(id != null && id > 0){
            num = stockMapper.updateById(stock);
        }else{
            num = stockMapper.insert(stock);
        }
        if(num > 0){
            return Response.successAndJump("/Stock/index");
        }else{
            return Response.error("操作失败");
        }

    }

    @GetMapping(value = {"/edit","/add"})
    public String edit(Integer id,ModelMap map){
    	System.out.println("id:"+id);
        if(null != id && id > 0){
            map.addAttribute("vo",stockMapper.selectById(id));
        }
        return "stock/edit";
    }


    @GetMapping("/lists")
    @ResponseBody
    public Object lists(Integer page, Integer limit){
        TableSet<Stock> datasets = new TableSet<>(page,limit);
        List<Stock> list = stockMapper.selectPage(datasets);
        return datasets.setRecords(list).response();
    }
//
    @GetMapping("doDel")
    @ResponseBody
    public Object doDel(Integer id){
//        int num = 0;
//        if(null != id && id > 0){
//            num = cateMapper.deleteById(id);
//        }
//        if(num > 0){
    	
    	List<Integer> list = new ArrayList<>();
    	list.add(2);
    	list.add(3);
    	list.add(4);
    	list.add(5);
    	list.add(6);
    	stockMapper.updateBatch(list);
            return Response.success();
//        }else{
//            return Response.error();
//        }
    }
}
